<?php

namespace seecms\wechat\lib;

use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Voice;
use Psr\Cache\InvalidArgumentException;
use seecms\See;

/**
 * 微信公众号事件
 */
class WechatEvent
{
    protected $app = '';

    protected $open_id = '';

    protected $content = [];

    protected $setting = [];

    public function __construct($app, $content)
    {
        $this->app = $app;
        $this->content = $content;

        $this->open_id = $content['FromUserName'];

        $this->setting = See::provider()->general->wechat;
    }

    /**
     * 用户关注事件
     */
    public function subscribe()
    {
        $subscribe = $this->setting['subscribe'] ?? '';

        if (empty($subscribe)) {
            return '';
        }

        $subscribe = json_decode($subscribe, true);

        $method = $subscribe['method'];
        $replay = $subscribe['replay'];
        if ($replay) {
            $app = $this->app;
            foreach ($replay as $item) {
                $type = $item['type'] ?? '';
                $content = $item['content'] ?? '';
                if (empty($type) || empty($content)) {
                    continue;
                }
                $message = null;
                if ($type === 'text') {
                    $message = new Text(WechatTransfer::wechatReplayContentFilter($content));
                } elseif ($type === 'image') {
                    $message = new Image($content);
                } elseif ($type === 'voice') {
                    $message = new Voice($content);
                }
                if (isset($message)) {
                    if ($method == 'response') {
                        return $message;
                    } else {
                        $app->customer_service->message($message)->to($this->open_id)->send();
                    }
                }
            }
            return '';
        }

        return '';
    }

    /**
     * 用户取消关注事件
     * @return null
     */
    public function unsubscribe()
    {
        return null;
    }

    /**
     * 用户点击菜单事件
     * @return void
     */
    public function click()
    {
        return $this->content['Event'];
    }

    /**
     * 参数二维码事件
     * 未关注的时候事件类型为subscribe，且EventKey有值
     * @return void
     * @throws InvalidArgumentException
     */
    public function scan()
    {
        $key = $this->message['EventKey'] ?? '';

        // 绑定微信
        if (preg_match('/^bind/', $key)) {
            $info = explode('_', $key);
            $user_id = $info[1] ?? '';
            if ($user_id) {
                try {
                    $user = See::table()->user->where('id', $user_id)->find();
                    if ($user) {
                        See::table()->user->where('id', $user_id)->data('wechat_openid', $this->open_id)->update();
                    }

                    $this->app->customer_service->message(new Text('微信绑定成功'))->to($this->open_id)->send();

                } catch (\Exception $exception) {

                }
            }
        } elseif (preg_match('/^login/', $key)) {
            try {
                $user = See::table()->user->where('wechat_openid', $this->open_id)->find();
                if ($user) {
                    // 设置登录信息
                    See::cache()->set($key, [
                        'expire_time' => time() + 600,
                        'user_id' => $user['id']
                    ]);
                    $this->app->customer_service->message(new Text('扫码登录完成'))->to($this->open_id)->send();
                }
            } catch (\Exception $exception) {

            }
        }
    }

    /**
     * 公众号自动上报地理位置（需要用户授权）
     * @return string
     */
    public function LOCATION(): string
    {
        $lat = $this->content['Latitude'] ?? '';
        $long = $this->content['Longitude'] ?? '';

        $message = new Text('收到了地理位置:' . "\n" . '   ' . $lat . " , " . $long);
        $this->app->customer_service->message($message)->to($this->open_id)->send();

        return '';
    }
}